<template>
  <div class="page-container">
    <!-- 按钮工具栏 -->
    <div class="button-toolbar">
      <el-button type="primary" @click="goBack" icon="el-icon-back"
        >返回</el-button
      >
      <span>
        <el-button
          type="success"
          @click="saveData"
          :disabled="isView"
          icon="el-icon-check"
          >保存</el-button
        >
        <el-button @click="goToList" icon="el-icon-menu">列表</el-button>
        <!-- <el-button type="info" @click="printToPDF" icon="el-icon-printer">打印PDF</el-button>
                  -->

        <el-button type="info" icon="el-icon-printer" @click="printForm"
          >打印</el-button
        >
      </span>
    </div>

    <!-- 表单内容 -->
    <div class="outpass-container">
      <div class="form-header">
        <h2>员工外出放行单</h2>
        <div class="form-info">
          <div class="form-info-item">
            <label>日期：</label>
            <el-date-picker
              v-model="formData.passDate"
              type="date"
              :disabled="isView"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
          <div class="form-info-item">
            <label style="white-space: nowrap">编号：</label>
            <el-input
              v-model="formData.passNumber"
              :disabled="isView"
            ></el-input>
          </div>
        </div>
      </div>

      <el-form :model="formData" label-width="120px" class="form-body">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="持单人姓名：">
              <el-input
                v-model="formData.holderName"
                :disabled="isView"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工号：">
              <el-input
                v-model="formData.employeeNumber"
                :disabled="isView"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门：">
              <el-input
                v-model="formData.department"
                :disabled="isView"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="外出事由：">
          <el-input
            type="textarea"
            v-model="formData.outReason"
            :disabled="isView"
            :rows="3"
          >
          </el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间：">
              <el-date-picker
                v-model="formData.startTime"
                type="datetime"
                :disabled="isView"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间：">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                :disabled="isView"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="组长签字：">
              <el-input
                v-model="formData.teamLeaderSignature"
                :disabled="isView"
              ></el-input>
            </el-form-item>
            <el-form-item label="签字日期：">
              <el-date-picker
                v-model="formData.teamLeaderDate"
                type="date"
                :disabled="isView"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门主管签字：">
              <el-input
                v-model="formData.departmentHeadSignature"
                :disabled="isView"
              ></el-input>
            </el-form-item>
            <el-form-item label="签字日期：">
              <el-date-picker
                v-model="formData.departmentHeadDate"
                type="date"
                :disabled="isView"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="值班保安签字：">
              <el-input
                v-model="formData.securitySignature"
                :disabled="isView"
              ></el-input>
            </el-form-item>
            <el-form-item label="签字日期：">
              <el-date-picker
                v-model="formData.securityDate"
                type="date"
                :disabled="isView"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="form-footer">
        <span>表单编号及版本：AM-JY-284 A/0</span>
        <span>保存期限：长期</span>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import {
  getEmployeeOutpassById,
  saveEmployeeOutpass,
} from "@/api/employeeOutpass";

export default {
  data() {
    return {
      isView: false,
      formData: {
        id: null,
        passDate: "",
        passNumber: "",
        holderName: "",
        employeeNumber: "",
        department: "",
        outReason: "",
        startTime: "",
        endTime: "",
        duration: 0,
        teamLeaderSignature: "",
        departmentHeadSignature: "",
        securitySignature: "",
        teamLeaderDate: "",
        departmentHeadDate: "",
        securityDate: "",
      },
    };
  },
  created() {
    const { id, type } = this.$route.query;
    if (id) {
      this.fetchData(id);
    }
    this.isView = type === "view";
  },
  methods: {
    printForm() {
      // 创建一个样式元素
      const style = document.createElement("style");
      style.type = "text/css";
      style.media = "print";
      style.textContent = "@page { size: A4 landscape; }";
      // 将样式添加到文档头部
      document.head.appendChild(style);
      // 执行打印
      window.print();
      // 打印完成后移除样式
      document.head.removeChild(style);
    },
    fetchData(id) {
      getEmployeeOutpassById(id).then((response) => {
        this.formData = response.data;
      });
    },
    validateForm() {
      if (!this.formData.holderName) {
        this.$message({
          type: "warning",
          message: "请输入持单人姓名",
        });
        return false;
      }
      if (!this.formData.employeeNumber) {
        this.$message({
          type: "warning",
          message: "请输入工号",
        });
        return false;
      }
      if (!this.formData.passDate) {
        this.$message({
          type: "warning",
          message: "请选择日期",
        });
        return false;
      }
      if (!this.formData.startTime || !this.formData.endTime) {
        this.$message({
          type: "warning",
          message: "请选择起止时间",
        });
        return false;
      }
      return true;
    },
    calculateDuration() {
      if (this.formData.startTime && this.formData.endTime) {
        const start = new Date(this.formData.startTime);
        const end = new Date(this.formData.endTime);
        this.formData.duration = Math.round((end - start) / 1000 / 60);
      }
    },
    saveData() {
      if (!this.validateForm()) {
        return;
      }

      this.calculateDuration();

      saveEmployeeOutpass([this.formData])
        .then(() => {
          this.$message({
            type: "success",
            message: "保存成功！",
          });
          this.$router.push(
            "/main/renshi/renshizhidu/ygwaichufxd/ygwaichufxdList"
          );
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: "保存失败：" + error.message,
          });
        });
    },
    printToPDF() {
      const doc = new jsPDF("p", "pt", "a4");
      const element = document.querySelector(".outpass-container");
      html2canvas(element).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");
        const imgWidth = 522;
        const pageHeight = 841.89;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let positionY = 0;
        if (imgHeight >= pageHeight) {
          let leftHeight = imgHeight;
          while (leftHeight >= pageHeight) {
            doc.addImage(imgData, "PNG", 40, positionY, imgWidth, pageHeight);
            positionY += pageHeight;
            doc.addPage();
            leftHeight -= pageHeight;
          }
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, leftHeight);
        } else {
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, imgHeight);
        }
        doc.save("员工外出放行单.pdf");
      });
    },
    goBack() {
      this.$router.push("/main/renshi/renshizhidu");
    },
    goToList() {
      this.$router.push("/main/renshi/renshizhidu/ygwaichufxd/ygwaichufxdList");
    },
  },
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  /* background-color: #f5f7fa; */
  min-height: calc(100vh - 40px);
  width: 291mm;
  margin: 0 auto;
}

.button-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 16px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.outpass-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin: 0 auto;
  max-width: 1200px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.form-header h2 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.form-info {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin-bottom: 20px;
}

.form-info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-body {
  padding: 20px;
}

.form-footer {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

:deep(.el-button) {
  padding: 12px 20px;
  font-size: 14px;
}

:deep(.el-button + .el-button) {
  margin-left: 12px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor--datetime) {
  width: 100%;
}

@media print {
  /* @page {
        size: A4 landscape;
    } */
  .button-toolbar {
    display: none;
  }
  .outpass-container {
    box-shadow: none !important;
  }
  ::v-deep input.el-input__inner {
    border: none !important;
  }
  ::v-deep textarea.el-textarea__inner {
    border: none !important;
    resize: none;
  }
  ::v-deep i.el-input__icon {
    display: none !important;
  }
}
</style>